package com.cedifie.lendapp.ui.user.impl

import android.content.Context
import com.cedifie.lendapp.MyApplication
import com.cedifie.lendapp.R
import com.cedifie.lendapp.http.ApiService
import com.cedifie.lendapp.http.ApiService.addCommonParams
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.http.IHttpCallback
import com.cedifie.lendapp.mvp.presenter.MvpPresenter
import com.cedifie.lendapp.ui.user.view.ICedUserCheckPhoneNumberView
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2025/4/11 10:41
 * @Annotation：校验手机号 Presenter 实现
 */
class CedUserCheckPhoneNumberPresenterImpl(context: Context?) : MvpPresenter<ICedUserCheckPhoneNumberView>(context) {

    private var model: CedUserCheckPhoneNumberModelImpl? = null
    init {
        model = CedUserCheckPhoneNumberModelImpl()
    }

    //选择类型  SMS、WHATSAPP、TELEGRAM、TGBOT
    private var selectType = ""
    //是否需要选择出生日期
    private var needSubmitBirthDay = "NO"

    fun getCheckNumberSelectType(): String{
        return selectType
    }

    /**
     * 是否需要验证生日
     */
    fun getCheckNumberNeedSubmitBirthDay(): String{
        return needSubmitBirthDay
    }

    /**
     * 切换校验类型
     */
    fun setCheckNumberType(type: String,isSend: Boolean = true){
        if (selectType == type){
            return
        }
        selectType = type
        mvpView?.showCedCheckPhoneNumberType(type,isSend)

        //如果校验类型是”TGBOT“，需要调接口获取Url去浏览器校验
        if ("TGBOT" == type){
            loadCedCheckPhoneNumberTypeTelegramBotLinkAction()
            return
        }
        if (isSend){
            sendCheckNumberWhatsAppCodeAction()
        }
    }

    /**
     * 发送WhatsApp验证码
     */
    fun sendCheckNumberWhatsAppCodeAction(){
        var phoneNumber = ""
        mvpView?.let {
            phoneNumber = it.getCedCheckPhoneNumber()
        }
        //发送验证，埋点增加手机号
        HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_VERIFICATION_GETCODE,phoneNumber)
        mvpView?.showCedLoading(MyApplication.app.getString(R.string.loading))
        model?.sendCheckNumberWhatsAppCodeAction(phoneNumber,selectType,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")){
                    0 -> {
                        val obj = data.optJSONObject("obj")
                        if (obj != null) {
                            //是否需要验证生日
                            if (obj.has("needSubmitBirthDay")){
                                needSubmitBirthDay = obj.optString("needSubmitBirthDay")
                            }
                            //当为YES时可以跳过，直接调用流程接口，根据流程步骤whatsappFlag标识走
                            val directLoginFlag = obj.optString("directLoginFlag")
                            mvpView?.showCedCheckPhoneNumberSendCodeSuccess(directLoginFlag)
                        }
                    }
                    else -> {
                        mvpView?.showCedToast(data.optString("msg"))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }

    /**
     * 当校验方式是”TGBOT“时，需要通过链接校验
     */
    fun loadCedCheckPhoneNumberTypeTelegramBotLinkAction(){
        var phoneNumber = ""
        mvpView?.let {
            phoneNumber = it.getCedCheckPhoneNumber()
            it.showCedLoading(MyApplication.app.getString(R.string.loading))
        }
        model?.loadCedCheckPhoneNumberTypeTelegramBotLinkAction(phoneNumber,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {
                        val obj = data.optJSONObject("obj")
                        if (obj != null) {
                            val link = obj.optString("url","")
                            mvpView?.showCedCheckPhoneNumberTelegramBotLink(link)
                        }
                    }
                    else -> {
                        mvpView?.showCedToast(data.optString("msg"))
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }

    /**
     * 校验验证码
     */
    fun onCheckNumberVerificationCodeAction(submitBirthDay: String = ""){
        //需要提交出生日期
        if (needSubmitBirthDay == "YES" && submitBirthDay.isEmpty()){
            mvpView?.showCedCheckPhoneNumberChooseBirthdayDialog()
            return
        }
        mvpView?.showCedLoading(MyApplication.app.getString(R.string.loading))
        val loginMobile = SharedHelper.getCedSPString(SharedHelper.CED_SPKEY.CEDIFIE_MOBILE)
        val params = JSONObject().addCommonParams().apply {
            put("path", ApiService.API_PATH.CED_API_WHATSAPP_CHECK_CODE_PATH)
            put("mobile", loginMobile)
            put("submitMobile", mvpView?.getCedCheckPhoneNumber())
            put("code",mvpView?.getCedCheckPhoneNumberCode())
            put("checkType",getCheckNumberSelectType())
            put("needSubmitBirthDay",needSubmitBirthDay)//是否需要验证生日
        }
        if (needSubmitBirthDay == "YES" && submitBirthDay.isNotEmpty()){
            params.put("submitBirthDay",submitBirthDay)//出生日期
        }
        model?.onCedCheckPhoneNumberVerificationCodeAction(params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {
                        mvpView?.hideCedLoading()
                        mvpView?.showCedCheckPhoneNumberSuccess()
                    }
                    else -> {
                        mvpView?.showCedToast(data.optString("msg"))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }
}